package com.roc.web.action.agent;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionContext;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.AuditingItem;
import com.roc.pojo.ModuleCategory;
import com.roc.pojo.Operators;
import com.roc.pojo.MerchantModuleRight;
import com.roc.pojo.OrgBean;
import com.roc.service.IMerchantServices;
import com.roc.service.IPagenitionService;
import com.roc.service.IorgService;
import com.roc.service.ServiceException;
import com.roc.service.agent.IAgentInfoService;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.constant.AuditingResultCodeType;
import com.roc.util.constant.AuditingType;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.OperatorsStatus;
import com.roc.util.constant.RespCode;
import com.roc.util.constant.Role;
import com.roc.util.constant.SexStatus;

/**
 * 
 * @author 陈锴
 * 
 * 代理商初审
 * 
 * 2014-08-10
 *
 */

@Component
@Scope("prototype")
@Namespace("/agentOne")
public class AgentAuditingOneAction extends PaginationBaseAction{
	
	private Logger logger=LogManager.getLogger(AgentAuditingOneAction.class);
	
	private AgentAuditingOneSearchCondition searchCondition;
	
	private Operators merchant;
	
	private AuditingItem auditing;
	
	private List<OrgBean> orgList=new ArrayList<OrgBean>();
	
	@Autowired
	IorgService orgService;
	
	@Autowired
	IPagenitionService pagenitionService;
	
	@Autowired 
	IMerchantServices merchantServices;
	
	@Autowired
	IPowerInfoService powerInfoService;
	
	@Autowired
	IAgentInfoService agentInfoService;
	
	@Action(value = "queryAgentOne", results = { @Result(name = "success", location = "/pages/agent/agentAuditingOneList.jsp")
             })
	public String queryAgentOneAction() throws Exception{
		
		org();
		
		return SUCCESS;
	}
	
	@Action(value = "queryAgentOneList", results = { @Result(name = "success", location = "/pages/agent/agentAuditingOneList.jsp")
           })
	//查询代理商
	public String queryAgentOneListAction() throws Exception{
		
        Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		
		if(searchCondition==null){
			searchCondition=(AgentAuditingOneSearchCondition)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition=new AgentAuditingOneSearchCondition();
			}
		}
		try {
			org();
			if(searchCondition.getRole().equals("99")){
				searchCondition.setRole(Role.AGENT.getCode()+","+Role.O_MANAGER.getCode());   //操作员类型查询  代理商  和  O单管理员
			}
			searchCondition.setStatus(OperatorsStatus.WAIT_AUDITING.getCode());  //查询代理商状态为  待审核   的
			int rows=pagenitionService.count(searchCondition);
			searchRsList=pagenitionService.findAll(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);

			agentTheListSpecially(searchRsList);
			
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
			
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			e.printStackTrace();
			addActionError(e.getMessage());
			return ERROR;
		}
		
		return SUCCESS;
	}
	
	@Action(value = "queryAgentViewOne", results = { @Result(name = "success", location = "/pages/agent/agentAuditingOneView.jsp")
            })
	//查询代理商详细信息
	public String queryAgentViewAction(){
		Operators operators=new Operators();
		
		try {
			merchant.setAccountNo(URLDecoder.decode(merchant.getAccountNo() , "UTF-8"));
			operators=agentInfoService.queryAgentInfo(merchant.getAccountNo());
			
			Map<String,String> auditingMap=new LinkedHashMap<String,String>();
			auditingMap.put(AuditingResultCodeType.PASS.getCode(),AuditingResultCodeType.PASS.getName());
			auditingMap.put(AuditingResultCodeType.REFUSE.getCode(),AuditingResultCodeType.REFUSE.getName());
			auditingMap.put(AuditingResultCodeType.INCOMPLETE_INFO.getCode(),AuditingResultCodeType.INCOMPLETE_INFO.getName());
			
			getRequest().setAttribute("auditingMap",auditingMap);
			
			getRequest().setAttribute("agent", operators);
			
			getRequest().setAttribute("agTypeList",ConfigProperties.getAgentTypeProperties());
			
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			e.printStackTrace();
			addActionError(e.getMessage());
			return ERROR;
		}
		
		
		return SUCCESS;
	}
	
	@Action(value = "agentAuditingOne", results = { @Result(name = "success", location = "/pages/agent/agentAuditingOneList.jsp")
             })
	//代理商审核
	public String agentAuditingOneAction() throws Exception{
		Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
				//获取操作员的ID
				String accountNo=merchant.getAccountNo();
				
				//编辑审核结果
				auditing.setAudit_code(AuditingType.AGENT_AUDITING.getCode());
				auditing.setAudit_name(AuditingType.AGENT_AUDITING.getName());
				auditing.setObj_Audited(accountNo);
				auditing.setOperators(logingMerchant.getAccountNo());
				//auditing.setResult_code(auditing.getAudit_code());
				//auditing.setResult_detail(auditing.getResult_detail());
				
				//当界面选择同意并且和枚举中的同意code相同时代表进入复审
				if(auditing.getResult_code().equals(AuditingResultCodeType.PASS.getCode())){
					merchant.setStatus(OperatorsStatus.WAIT_RE_AUDITING.getCode());  //复审
				}else{
					merchant.setStatus(OperatorsStatus.INCOMPLETE_INFO.getCode());  //初审失败
				}
				
				//调用service层
				try {
					agentInfoService.agentAuditingOneInfo(auditing, logingMerchant.getAccountNo(), merchant.getStatus());
					
					logger.info("------------------------------操作员【"+logingMerchant.getAccountNo()+"】审核【"+merchant.getAccountNo()+"】成功！-----------------------------------");
				} catch (ServiceException e) {
					logger.info("------------------------------操作员【"+logingMerchant.getAccountNo()+"】初审【"+merchant.getAccountNo()+"】失败！-----------------------------------");
					logger.error(e.getMessage(),e);
					return ERROR;
				}
				return queryAgentOneListAction();
	}
	
	//查询机构
	public void org() throws Exception{
		   Operators operators = (Operators) ActionContext.getContext().getSession().get(Constant.SESSION_LOGIN_MERCHANT);
		   
			orgList=orgService.listOrgs(operators);
			
			getRequest().setAttribute("orgList", orgList);
			
			Map<String, String> merLevels=ConfigProperties.getAgentTypeProperties();
			getRequest().setAttribute("merLevels", merLevels);
			
			//加载角色类型     只查询代理商和O单管理员
			Map roleMap=new HashMap();
			roleMap.put(Role.O_MANAGER.getCode(),Role.O_MANAGER.getName());
			roleMap.put(Role.AGENT.getCode(),Role.AGENT.getName());
			
			getRequest().setAttribute("roleMap",roleMap);
		
	}
	
	protected void agentTheListSpecially(List<Object> list) {
    	List<Object> tempList=new ArrayList<Object>();
		for(Object obj:list){
			Operators temp=(Operators)obj;
			for(OrgBean bean:orgList){
				if(temp.getOrgCode().equals(bean.getOrg_code())){
					temp.setOrgName(bean.getOrg_name());
				}
			}
			temp.setSex(SexStatus.valueOfCode(temp.getSex()).getName());
			temp.setRoleName(Role.valueOfCode(temp.getRoleType()).getName());
			temp.setStatus(OperatorsStatus.valueOfCode(temp.getStatus()).getName());
			tempList.add(temp);
		}
		searchRsList=tempList;
		
	}
	
	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE+"";
	}

	/* (non-Javadoc)
	 * @see com.roc.page.PaginationBaseAction#getSearchConditionFromSession()
	 */
	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (AgentAuditingOneSearchCondition)getSession().getAttribute(SEARCH_SESSION_BEAN_AGENT_AUDITING_ONE);
	}

	/* (non-Javadoc)
	 * @see com.roc.page.PaginationBaseAction#getSearchConditionFromSubClass()
	 */
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	/* (non-Javadoc)
	 * @see com.roc.page.PaginationBaseAction#setSearchConditionToSubClass(com.roc.page.BaseSearchCondition)
	 */
	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
	}

	/* (non-Javadoc)
	 * @see com.roc.page.PaginationBaseAction#setSearchToConditionSession(com.roc.page.BaseSearchCondition)
	 */
	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_BEAN_AGENT_AUDITING_ONE, searchCondition);
	}

	public Operators getMerchant() {
		return merchant;
	}

	public void setMerchant(Operators merchant) {
		this.merchant = merchant;
	}

	public AgentAuditingOneSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(AgentAuditingOneSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public AuditingItem getAuditing() {
		return auditing;
	}

	public void setAuditing(AuditingItem auditing) {
		this.auditing = auditing;
	}

	public List<OrgBean> getOrgList() {
		return orgList;
	}

	public void setOrgList(List<OrgBean> orgList) {
		this.orgList = orgList;
	}


}
